import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:web_container/config/logger.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {

  final String title;
  final String url;
  const WebViewPage({Key? key, required this.title, required this.url}) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> 
    with AutomaticKeepAliveClientMixin {

  late ValueNotifier<String> _titleVn;
  late Set<JavascriptChannel> _jsChannels;
  late WebViewController _webViewController;

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    super.dispose();
    _webViewController.clearCache();
  }

  @override
  void initState() {
    super.initState();
    Logger.i('START ${widget.title}');

    // JS 调用原生
    _jsChannels = {
      // 设置标题
      JavascriptChannel(
        name: 'setTitle',
        onMessageReceived: (JavascriptMessage message) {
          Logger.i('setTitle message=${message.message}');
          _titleVn.value = message.message;
        }),
    };
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    
    return Scaffold(
      appBar: null,
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[];
        },
        body: WebView(
          backgroundColor: Colors.white,
          initialUrl: widget.url,
          zoomEnabled: false,
          javascriptMode: JavascriptMode.unrestricted,  // 启用 JS
          javascriptChannels: _jsChannels,
          gestureRecognizers: {
            // 解决滑动冲突
            Factory<VerticalDragGestureRecognizer>(() => VerticalDragGestureRecognizer()),
          },
          onWebViewCreated: (controller) {
            _webViewController = controller;
          },
          onPageFinished: (String url) {
            // 开始执行js注入
            // var num = '0';
            // webViewController.runJavascriptReturningResult("setPageType('$num')")
            //   .then((String result) {
            //     setState(() {});
            //   });
          },
        ),
      ),
    );
  }
}
